//
//  LoadingViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/5/23.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "LoadingViewModel.h"

#import <CoreLocation/CoreLocation.h>
#import <LMGeocoder/LMGeocoder.h>
#import <AFNetworking/AFNetworking.h>

#import "UserInfoData.h"
#import "ProvincesListData.h"
#import "CategorysData.h"
#import "DeclarationInfosData.h"
#import "UserCenterInfoData.h"

@interface LoadingViewModel() <CLLocationManagerDelegate>

@property (nonatomic, strong) RACCommand* loadFinishCmd;

@property (nonatomic, strong) CLGeocoder *geocoder;

@end

@implementation LoadingViewModel

- (void)initialize
{
    [super initialize];
    
    _isNetLinked = NO;
    _strAddr = @"";
    
    @weakify(self);
    
    _reqGeoCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
#if TARGET_IPHONE_SIMULATOR
        //iPhone Simulator
        self.strAddr = HCStrFormat(@"%@-%@-%@", @"广东省", @"汕头市", @"龙湖区");
#else
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 100.0f;
        if ([[[UIDevice currentDevice] systemVersion] doubleValue] >8.0)
        {
            [self.locationManager requestWhenInUseAuthorization];
        }
        [self.locationManager startUpdatingLocation];
#endif
        
        return [RACSignal empty];
    }];
    
    RACSignal* locationSucSignal = [[RACObserve(self, strAddr) distinctUntilChanged] filter:^BOOL(id value) {
        
        NSString* strValue = value;
        
        DataManager* dataMgr = [DataManager sharedDataManager];
        dataMgr.address = strValue;
        
        return [strValue isNotBlank];
    }];
    
    RACSignal* netLinkedSignal = [self rac_signalForSelector:@selector(netIsConnect)];
    
    [[locationSucSignal flattenMap:^RACStream *(id value)
    {
        return [[[[[RACSignal interval:1 onScheduler:[RACScheduler scheduler]]
                 takeUntil:netLinkedSignal]
                flattenMap:^RACStream *(id value) {
                    
                    return [[AFNetWorkUtils sharedAFNetWorkUtils] startMonitoringNetComplete];
                }] map:^id(id value) {
                    
                    NSString* strNetType = value;
                    
                    NSLog(@"NetType : %@", strNetType);
                    
                    return @([strNetType isEqualToString:@"2G/3G/4G"] || [strNetType isEqualToString:@"WIFI"]);
                }] map:^id(id value) {
                    
                    BOOL isNetConnect = [value boolValue];
                    
                    if (isNetConnect)
                    {
                        [self netIsConnect];
                    }
                    
                    return value;
                }];
    }] subscribeNext:^(id x) {
        
        @strongify(self);
        
        NSLog(@"%@",[NSDate date]);
        
        if ([x boolValue])
        {
            //网络已经链接
            NSLog(@"网络已经链接");
            
            [self.loadFinishCmd execute:nil];
        }
    }];
    
    self.loadFinishCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        @weakify(self);
        RACSignal* delaySignal = [[[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
        {
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            return nil;
        }] delay:3.0f] map:^id(id value) {
            
            return @"DelayOver";
        }];
        
        return [[self requestAllNeedDataSignal] zipWith:delaySignal];
    }];
    
    [self.loadFinishCmd.executionSignals.switchToLatest subscribeNext:^(id x)
    {
        @strongify(self);
        
        if ([x isKindOfClass:[RACTuple class]])
        {
            RACTuple* tuple = x;
            
            id strCheckLoading = tuple.first;
            
            if ([strCheckLoading isKindOfClass:[NSString class]] && [strCheckLoading isEqualToString:@"LoadingOver"])
            {
                NSLog(@"Ready 2 loadingOver");
                [self loadingOver];
            }
        }
    } completed:^
    {
        NSLog(@"Completed");
    }];
}

- (RACSignal *)requestAllNeedDataSignal
{
    @weakify(self)
    
    RACSignal* userInfoSignal = [self _requestUserInfoSignal];
    RACSignal* addrInfoSignal = [self _requestGetPCA];
    RACSignal* cateInfosSignal = [self _reqCateListSignal];
    RACSignal* publicityCateInfosSignal = [self _requestHBNoticeTypeSignal];
    RACSignal* declarationInfosSignal = [self _reqDeclarationListSignal];
    
    return [[[[userInfoSignal then:^RACSignal *
    {
        return cateInfosSignal;
    }] then:^RACSignal *
    {
        return publicityCateInfosSignal;
    }] then:^RACSignal *
    {
        return declarationInfosSignal;
    }] then:^RACSignal *
    {
        return addrInfoSignal;
    }];
}

- (RACSignal*)requestHeadUrlSignal
{
    @weakify(self);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self)
                
                @weakify(self);
                [[AFNetWorkUtils racDOWNLOADWthURL:@"http://huan-ju.com/hb/config.txt" savePath:@"SysConfig/config.txt"]
                 subscribeNext:^(id x)
                {
                    @strongify(self);
                }
                 completed:^
                {
                    @strongify(self);
                    
                    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    NSString *path = [paths objectAtIndex:0];
                    
                    NSString *filePath = [path stringByAppendingPathComponent:@"SysConfig/config.txt"];
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    
                    BOOL result = [fileManager fileExistsAtPath:filePath];
                    if(!result)
                    {
                        NSLog(@"文件不存在");
                    }
                    else
                    {
                        NSLog(@"文件存在");
                    }
                    
                    NSString *content = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
                    NSLog(@"配置文件内容：%@", content);
                    
                    NSDictionary* contentDic = [content jsonValueDecoded];
                    
                    [UrlManager sharedUrlManager].configData = contentDic;
                    
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }];
                
                return nil;
            }];
}

//- (void)showAllFileWithPath:(NSString *) path
//{
//    NSFileManager * fileManger = [NSFileManager defaultManager];
//    BOOL isDir = NO;
//    BOOL isExist = [fileManger fileExistsAtPath:path isDirectory:&isDir];
//    if (isExist) {
//
//        NSArray * dirArray = [fileManger contentsOfDirectoryAtPath:path error:nil];
//        NSString * subPath = nil;
//        for (NSString * str in dirArray) {
//            subPath  = [path stringByAppendingPathComponent:str];
//
////            NSString *fileName = [[path componentsSeparatedByString:@"/"] lastObject];
//            NSLog(@"SubPath - %@", subPath);
//
//            BOOL issubDir = NO;
//            [fileManger fileExistsAtPath:subPath isDirectory:&issubDir];
//            [self showAllFileWithPath:subPath];
//        }
//    }else{
//        NSLog(@"this path is not exist!");
//    }
//}

- (RACSignal*)_requestUserInfoSignal
{
    @weakify(self)
    
    UserManagerV2* userMgr = [UserManagerV2 sharedUserManagerV2];
    
    if (![userMgr isHaveUserToken])
    {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
    {
        @strongify(self)
        
        NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
        //    strUserToken = @"619DB322B2F7B9365C31FC9774FF2FA7";
        //    strUserToken = @"348802CEEE3E15CEE0C1CDCA1E0F8086";
        NSString* userID = [userDefaults objectForKey:@"UserToken"];
        
        @weakify(self);
        [[AFNetWorkUtils racPOSTWthURL:url_interface_userInfo params:interface_param_userInfo(userID)] subscribeNext:^(id x)
         {
             @strongify(self)
             
             UserInfoData* userData = [UserInfoData modelWithJSON:x];
             
             [userMgr updateUserToken:userData.userID];
             
             NSLog(@"UserInfoSignal - Finish");
             
             [subscriber sendNext:@YES];
             [subscriber sendCompleted];
         }  error:^(NSError *error) {
             //错误处理
             
             [userMgr clean];
             
             [subscriber sendNext:@NO];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal*)requestFilterInfosDataSignal
{
    //查找分类列表
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        @weakify(self);
        [[AFNetWorkUtils racGETWthURL:url_interface_getfilterlist] subscribeNext:^(id x)
         {
             @strongify(self)
             
             DataManager* dm = [DataManager sharedDataManager];
             
             dm.filterInfos = [FilterInfosData modelWithJSON:x];
             
             NSLog(@"FilterInfoSignal - Finish");
             
             [subscriber sendNext:@YES];
             [subscriber sendCompleted];
         }  error:^(NSError *error) {
             //错误处理
             
             [subscriber sendNext:@NO];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal*)requestPollutantDataSignal:(NSInteger)type
{
    //查找分类列表
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        @weakify(self);
        [[AFNetWorkUtils racGETWthURL:[NSString stringWithFormat:@"%@%@", url_interface_gettaxrates, interface_param_gettaxrates((int)type)]] subscribeNext:^(id x)
         {
             @strongify(self)
             
             PollutantData* pollutantData = [PollutantData modelWithJSON:x];
             
             DataManager* dm = [DataManager sharedDataManager];
             
             dm.pollutantDatas[dm.pollutantDatas.count] = pollutantData;
             
             NSLog(@"PollutantInfoSignal %d - Finish", (int)type);
             
             [subscriber sendNext:@YES];
             [subscriber sendCompleted];
         }  error:^(NSError *error) {
             //错误处理
             
             [subscriber sendNext:@NO];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal*)requestGetSubPCA:(ProvinceListData*)parentData
{
    @weakify(self);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
    {
        @strongify(self);
        
        [[AFNetWorkUtils racPOSTWthURL:url_interface_getcitylist params:interface_param_getcitylist(parentData.areaID)] subscribeNext:^(id x) {
            
            ProvincesListData* listData = [ProvincesListData modelWithJSON:x];
            
            parentData.datas = listData.datas;
            
            [subscriber sendNext:@YES];
            [subscriber sendCompleted];
            
            NSLog(@"Province areaID is %@", parentData.areaID);
            
        } error:^(NSError *error) {
            
            NSLog(@"");
        }];
        
        return nil;
    }];
}

- (RACSignal*)_requestGetPCA
{
    //查找分类列表
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        @weakify(self);
        
        NSLog(@"开始调用网络接口");
        
        [[[AFNetWorkUtils racPOSTWthURL:url_interface_getprovincelist params:@""] map:^NSArray *(id value)
         {
             ProvincesListData* addrData = [ProvincesListData modelWithJSON:value];

             DataManager* dm = [DataManager sharedDataManager];
             dm.addrData = addrData;
             
             @strongify(self);

             @weakify(self);
             return addrData.datas;
//             return [addrData.datas.rac_sequence map:^RACSignal* (ProvinceListData* curData)
//             {
//                 @strongify(self);
//
//                 return [self requestGetSubPCA:curData];
//             }].array;

         }]/* flattenMap:^RACStream *(id value) {

             NSArray* signals = value;
             
             RACSignal* resultSignal = signals[0];
             
             for (NSInteger index=1; index<signals.count; index++)
             {
                 RACSignal* curSignal = signals[index];
                 
                 resultSignal = [resultSignal then:^RACSignal *{
                     return curSignal;
                 }];
             }

             return resultSignal;
         }]*/ subscribeNext:^(id x)
         {
             [subscriber sendNext:@"LoadingOver"];
             [subscriber sendCompleted];
         } error:^(NSError *error)
         {
             NSLog(@"");
         }];
        
        return nil;
    }];
}

- (RACSignal*)requestGetEnterpriseType
{
    //查找分类列表
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        @weakify(self);
        [[AFNetWorkUtils racGETWthURL:[NSString stringWithFormat:@"%@%@", url_interface_getenterprisecategorys, interface_param_getenterprisecategorys()]] subscribeNext:^(id x)
         {
             @strongify(self)
             
             CategorysData* enterpriseTypeData = [CategorysData modelWithJSON:x];
             
             DataManager* dMgr = [DataManager sharedDataManager];
             dMgr.enterpriseCategorys = enterpriseTypeData;
             
             [subscriber sendNext:@YES];
             [subscriber sendCompleted];
         }  error:^(NSError *error) {
             //错误处理
             
             [subscriber sendNext:@NO];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

// 获取文库分类列表
- (RACSignal*)_reqCateListSignal
{
    @weakify(self);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_getlibrarylist params:@""] subscribeNext:^(id x)
                 {
                     @strongify(self);
                     
                     CateInfosData* data = [CateInfosData modelWithJSON:x];
                     
                     DataManager* dm = [DataManager sharedDataManager];
                     dm.libraryCateInfos = data;
                     
                     [subscriber sendNext:@YES];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

// 获取
- (RACSignal*)_reqDeclarationListSignal
{
    @weakify(self);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_getdeclarationlist params:@""] subscribeNext:^(id x)
                 {
                     @strongify(self);
                     
                     DeclarationInfosData* data = [DeclarationInfosData modelWithJSON:x];
                     
                     DataManager* dm = [DataManager sharedDataManager];
                     dm.declarationInfos = data;
                     
                     [subscriber sendNext:@YES];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

// 获取环保类型
- (RACSignal*)_requestHBNoticeTypeSignal
{
    @weakify(self);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_noticetype params:@""] subscribeNext:^(id x)
                 {
                     @strongify(self);
                     
                     CateInfosData* data = [CateInfosData modelWithJSON:x];
                     
                     DataManager* dm = [DataManager sharedDataManager];
                     dm.publicityCateInfos = data;
                     
                     [subscriber sendNext:@YES];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

#pragma mark - 功能
- (void)loadingOver
{
    self.isNetLinked = YES;
    
    // 用户配置
    [UserManagerV2 sharedUserManagerV2];
    
    // 全局数据初始化
    [DataManager sharedDataManager];
    
    // websocket 初始化
//    [SocketManager sharedSocketManager];
}

#pragma mark -- 定位
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status)
    {
        case kCLAuthorizationStatusNotDetermined:
        {
            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
            {
                [self.locationManager requestWhenInUseAuthorization];
            }
        }
            break;
            
        case kCLAuthorizationStatusDenied:
        {
            self.strAddr = HCStrFormat(@"%@-%@-%@", @"广东省", @"汕头市", @"龙湖区");
            
            [MBProgressHUD mh_showTips:@"为了您正常使用应用，我们建议您授权定位权限，当前应用将使用默认地址呈现数据内容"];
        }
            break;
            
        default:
            break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *newLocation = locations[0];
    
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    
    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    
    [self.locationManager stopUpdatingLocation];
    self.locationManager = nil;
    
    self.geocoder = [[CLGeocoder alloc] init];
    
    @weakify(self)
    
    CLLocation *checkLocation = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
    
//    [[LMGeocoder sharedInstance] reverseGeocodeCoordinate:checkLocation.coordinate service:kLMGeocoderAppleService completionHandler:^(NSArray<LMAddress *> * _Nullable results, NSError * _Nullable error)
//    {
//        @strongify(self);
//
//        if (results.count>0 && !error)
//        {
//            LMAddress* place = [results firstObject];
//
////            NSLog(@"name,%@",place.name);                      // 位置名
////            NSLog(@"thoroughfare,%@",place.thoroughfare);      // 街道
////            NSLog(@"subThoroughfare,%@",place.subThoroughfare);// 子街道
//            NSLog(@"subLocality,%@",place.subLocality);        // 区
//            NSLog(@"locality,%@",place.locality);              // 市
//            NSLog(@"locality,%@",place.administrativeArea);    // 省
//            NSLog(@"country,%@",place.country);                // 国家
//#if TARGET_IPHONE_SIMULATOR
//            //iPhone Simulator
//            self.strAddr = HCStrFormat(@"%@-%@-%@", @"广东省", @"汕头市", @"龙湖区");
//#else
//            if ([place.locality isNotBlank])
//            {
//                self.strAddr = HCStrFormat(@"%@-%@-%@", place.administrativeArea, place.locality, place.subLocality);
//            }
//            else
//            {
//                self.strAddr = HCStrFormat(@"%@-%@-%@", place.administrativeArea, place.administrativeArea, place.subLocality);
//            }
//#endif
//        }
//    }];
    
    [self.geocoder reverseGeocodeLocation:checkLocation completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError * _Nullable error)
    {
        @strongify(self)

        self.geocoder = nil;

        if (error)
        {
//            [self.reqGeoCmd execute:nil];

            self.strAddr = HCStrFormat(@"%@-%@-%@", @"广东省", @"汕头市", @"龙湖区");
            
            return;
        }

        for (CLPlacemark *place in placemarks) {

            NSLog(@"name,%@",place.name);                      // 位置名
            NSLog(@"thoroughfare,%@",place.thoroughfare);      // 街道
            NSLog(@"subThoroughfare,%@",place.subThoroughfare);// 子街道
            NSLog(@"subLocality,%@",place.subLocality);        // 区
            NSLog(@"locality,%@",place.locality);              // 市
            NSLog(@"locality,%@",place.administrativeArea);    // 省
            NSLog(@"country,%@",place.country);                // 国家
            
            if (![place.country isEqualToString:@"中国"])
            {
                self.strAddr = HCStrFormat(@"%@-%@-%@", @"广东省", @"汕头市", @"龙湖区");
                
                break;
            }

#if TARGET_IPHONE_SIMULATOR
            //iPhone Simulator
            self.strAddr = HCStrFormat(@"%@-%@-%@", @"广东省", @"汕头市", @"龙湖区");
#else
            if ([place.locality isNotBlank])
            {
                self.strAddr = HCStrFormat(@"%@-%@-%@", place.administrativeArea, place.locality, place.subLocality);
            }
            else
            {
                self.strAddr = HCStrFormat(@"%@-%@-%@", place.administrativeArea, place.administrativeArea, place.subLocality);
            }
#endif
            break;
        }
    }];
}

- (void)netIsConnect
{}

- (BOOL)isOpenLocation
{
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] ==kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] ==kCLAuthorizationStatusAuthorized))
    {
        return YES;
    }
    else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied)
    {
        return NO;
    }
    else
    {
        return NO;
    }
}

@end
